//
//  QuantitySelectorView.swift
//  Box
//
//  Created by mn on 2025/4/4.
//
import UIKit
import SnapKit

class QuantitySelectorView: UIView {
    
    private func createButton(title: String) -> UIButton {
        let button = UIButton()
        button.setTitle(title, for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 25)
        button.backgroundColor = .init(hex: "#F4F6F8")
        button.layer.cornerRadius = 5
        return button
    }
    
    lazy var minusButton = createButton(title: "−")
    lazy var plusButton = createButton(title: "+")
    
    private let countLabel: UILabel = {
        let label = UILabel()
        label.text = "1"
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        label.textAlignment = .center
        return label
    }()
    
    var countChanged:((Int) -> Void)?
    var count: Int = 1 {
        didSet {
            countLabel.text = "\(count)"
            countChanged?(count)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        addSubview(minusButton)
        addSubview(countLabel)
        addSubview(plusButton)
        
        minusButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 30, height: 30))
            make.left.centerY.equalToSuperview()
        }
        
        countLabel.snp.makeConstraints { make in
            make.left.equalTo(minusButton.snp.right).offset(8)
            make.centerY.equalToSuperview()
            make.width.equalTo(30)
        }
        
        plusButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 30, height: 30))
            make.left.equalTo(countLabel.snp.right).offset(8)
            make.right.centerY.equalToSuperview()
        }
        
        minusButton.addTarget(self, action: #selector(decreaseCount), for: .touchUpInside)
        plusButton.addTarget(self, action: #selector(increaseCount), for: .touchUpInside)
    }
    
    @objc private func decreaseCount() {
        if count > 1 {
            count -= 1
        }
    }
    
    @objc private func increaseCount() {
        if count < 10 {
            count += 1
        }
    }
}
